<?php
namespace app\common\model;

use think\Model;
use think\Exception;
use app\common\exception\APIException;

class DataUser extends Model
{
	protected $table = 'data_user';
	// 设置主键字段
	protected $pk = 'id';
	// 设置字段缓存
	// protected $schema = [
	// 	'id'	=> 'int',
	// 	'realname'		=> 'string',
	// 	'amount'		=> 'int',
	// 	'remark'		=> 'str',
	// 	'status'		=> 'int',
	// 	'create_time'	=> 'int',
	// ];

	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = true;

	// 验证唯一性
	static function checkMobile($mobile){
        $user = self::where('mobile',$mobile)->findOrEmpty();
        if($user->isEmpty()){
            return 0;
        } else {
        	return 1;
        }
    }

    static function mobileLogin() {
    	
    }

	static function wxappUserReg($mobile, $realname, $avatar, $wxdata)
	{
		// 判断用户信息是否已经存在
		try {
			$result = self::where('mobile', $mobile)->findOrEmpty();
			if (!$result->isEmpty()) {
				// return success(1001, "手机号已注册");die();
				apiException(20001);
				// throw new APIException([], 1);
			}
		} catch(\Exception $e){
			return $e->getMessage();
		} catch(\think\exception\HttpException $e) {
			return $e->getMessage();
		}
		// throw new APIException([],1);

		

		$user = self::create([
			'mobile' => $mobile,
			'realname' => $realname,
			'avatar' => $avatar,
			'status' => 0
		]);
		// 关联写入 together
		if ($user['id'] != 0) {
			// $user->profile->save($wxdata);
			// $res = self::find($user['id']);
			// $res->profile()->save(['company' => "江苏三仪"]);
			// $res->profile->section = "企划中心";
			// 更新当前模型及关联模型
			// $user->profile()->save(['section' => "企划中心", 'company' => "江苏三仪"]);
			$user->profile()->save($wxdata);
		}

		return $user;
	}

	// 一对一关联
	public function profile()
	{
		return $this->hasOne(DataUserProfile::class, 'user_id', 'id');
	}

	public function wxapp()
	{
		return $this->hasOne(DataUserWxapp::class, 'user_id', 'id');
	}
	
}